var app = getApp();
var util = require('../../utils/util.js');
import { averageUser, dealers } from '../../utils/tabBarUrl'
import {date,years,months,days,today} from '../../utils/date';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    page:1,
    page_count:1,
    status: 0,  //最新0，历史订单和历史小单1
    order_list:[],  //待编辑订单列表
    datas: [],     //订单列表
    load:'加载中...',
    loading:1,  //正在加载
    isshou_hint:false, //收货提醒
    screen_type_list1:{'1':'待接单','4':'待收货'},
    screen_type_list2:{'7':'已完成','6':'取消','rt2':'已退单'},
    z_screen_type_index:-1001,
    screen_type_index:-1001,
    screen_area_list:['过去一天','过去一周','过去一月'],
    z_screen_area_index:-1,
    screen_area_index:-1,
    area_time:0, //时间段开始时间
    is_screen:false,  //筛选下拉
    z_choose_supplier_id:0,   //筛选供应商id
    z_choose_supplier_name:'',
    choose_supplier_id:0,  //筛选供应商id
    // 时间周期********
    years,
    year: date.getFullYear(),
    months:months,
    month: 2,
    days:days,
    day: 2,
    value: [date.getFullYear() - 2010, date.getMonth(), date.getDate() - 1],  //默认今天
    time_type: 0,  //时间time切换的初始索引值
    start_time: 0,  //开始时间
    today:today, //今天
    end_time:today,    //结束时间,默认今天
    z_start_time:0, //选择开始时间
    z_end_time:today,   //选择结束时间,默认今天
    c_start_time: 0,  //右窗开始时间
    c_end_time:today, //结束时间,默认今天
    // *****
    new_hint_num:0,  //新订单数量
    shou_hint_num:0,  //待收货数量
    dui_hint_num:0   //对账的数量
  },
  noneEnoughPeople:function() {
    return;
  },
  //顶部导航切换
  typeTap: function(event) {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0
    });
    this.setData({
      page:1,
      status: event.currentTarget.dataset.index,
      helist:[],
      datas:[],
      order_list:[],
      load:'加载中...',
      loading:1
    });
    app.globalData.task.abort();
    if(app.globalData.loginInfo.client_is_store<0 && app.globalData.type_level==0 || app.globalData.loginInfo.client_is_store==0){
      this.ShouHuoCount();
    };
    this.updateList();  
  },
  // 去审批管理
  tocheck_order:function(){
    app.tocheck_manage(this.data.check_order_ids,this.data.purchase_order_ids,this.data.receipt_order_ids);
  },
  // 关闭审批提醒
  close_check_hint:function(){
    this.setData({
      is_check_hint:false
    });
  },
  // 点击进入需求单详情
  to_need_detail: function(event) {
    var id = event.currentTarget.dataset.id;
    var index = event.currentTarget.dataset.index;
    let order_status = event.currentTarget.dataset.order_status;
    var small_type=event.currentTarget.dataset.small_type;
    var charge_id=event.currentTarget.dataset.charge_id;
    var out_ku=order_status==2 && (this.data.loginInfo.is_manage==2 || this.data.use_person_id == charge_id)?1:0;   
    wx.navigateTo({
      url: 'need_detail/need_detail?id=' + id + "&order_status=" + order_status +'&small_type='+small_type+'&out_ku='+out_ku+"&d_index=" + index
    });  
  },
  // 点击进入订单详情
  to_dingdandetail(event) {
    var id = event.currentTarget.dataset.id;
    var index = event.currentTarget.dataset.index;
    let order_status = event.currentTarget.dataset.order_status;
    var is_cancel_apply = event.currentTarget.dataset.is_cancel_apply;
    var is_enquiry=event.currentTarget.dataset.is_enquiry;
    var is_created=event.currentTarget.dataset.is_created; 
    var is_substitute=event.currentTarget.dataset.is_substitute;
    if(order_status==0 && is_enquiry==0){
      if(is_substitute==1){
        wx.showModal({
          title: '提示',
          content: "此单为代下单\n对方正在编辑订单中",
          showCancel: false,
          confirmText:"我知道了",
          success: function (res) {}
        });
      }else if(is_substitute==0){
        wx.showModal({
          title: '提示',
          content: "此单为录单时\n创建的待编辑订单\n您可前往录单处确认下单",
          showCancel: false,
          confirmText:"我知道了",
          success: function (res) {}
        });
      };
      return;
    };
    if (is_cancel_apply!=1){
      wx.navigateTo({
        url: 'order_detail/order_detail?id=' + id + "&order_status=" + order_status+ "&settitle=" + "订单" + "&title_index=" + 1+"&is_enquiry="+is_enquiry+"&is_created="+is_created+"&d_index=" + index
      });
    }else{
      wx.showLoading({
        title: '等待对方确定',
        duration: 500
      });
    }    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function() {  
    app.globalData.toneed_order=0;
    this.setData({
      use_person_id:app.globalData.person_id, //当前用户的个人id
      raplace_h:0.75*wx.getSystemInfoSync().windowHeight
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    app.globalData.caigou_shua=1;
    this.setData({
      loginInfo:app.globalData.loginInfo,
      type_level:app.globalData.type_level,
      client_is_store:app.globalData.loginInfo.client_is_store,
      bar_list:app.globalData.loginInfo.client_is_store<0 && app.globalData.type_level==1 || app.globalData.loginInfo.client_is_store==1?{0:'新需求单',10:'历史记录'}:{0:'新订单',4:'待收货',10:'对账',11:'完成'},
      height: 630 / 750 * wx.getSystemInfoSync().windowWidth
    });
    wx.setNavigationBarTitle({
      title: app.globalData.loginInfo.client_is_store<0 && app.globalData.type_level==1 || app.globalData.loginInfo.client_is_store==1?"需求单":"订单"
    });
    if(app.globalData.loginInfo.client_is_store<0 && app.globalData.type_level==0 || app.globalData.loginInfo.client_is_store==0){      
      app.globalData.list =  averageUser;     //无需求单和库存
    }else if(app.globalData.loginInfo.client_is_store<0 && app.globalData.type_level==1 || app.globalData.loginInfo.client_is_store==1){
      app.globalData.list =  dealers;            //有需求单和库存 
    }; 
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        type_level:app.globalData.type_level,
        is_manage:app.globalData.loginInfo.is_manage,  //是否为管理员
        ischarge:app.globalData.loginInfo.ischarge,  //库管 是1 否0
        is_purchase_check:app.globalData.loginInfo.is_purchase_check,  //采购单审核  是1 否0
        selected: 1,
        list: app.globalData.list,
        // red:1
      })
    };    
    if(app.globalData.loginInfo.client_is_store<0 && app.globalData.type_level==0 || app.globalData.loginInfo.client_is_store==0){  //角标数量必刷新
      app.AppHttp("api/Order/daiShouHuoCount", { 
        client_id: app.globalData.loginInfo.id, 
      }, function (res) {
        that.setData({
          shou_hint_num:res.data.data
        });
        if(res.data.status==1){
          that.setData({
            isshou_hint:true
          });
          // setTimeout(function() {
          //   that.setData({
          //     isshou_hint:false
          //   });
          // }, 5000);
        }       
      });
      that.count_hint();   
    };
    if (app.globalData.dingdan_show == 1){  //判断返回时是否需要刷新   
      if(app.globalData.loginInfo.client_is_store<0 && app.globalData.type_level==1 || app.globalData.loginInfo.client_is_store==1){
        app.get_count_list(that);
        that.setData({
          is_check_hint:true
        });
      }
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 0
      });
      if(app.globalData.toneed_order==1 || app.globalData.postDataArr){
        this.setData({
          status:0
        });
      };
      if(app.globalData.postDataArr){
        delete app.globalData.postDataArr;
      };
      this.setData({
        page:1,
        load:'加载中...',       
      });
      this.updateList();
      app.globalData.toneed_order==0;
    };   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.updateList();
    wx.stopPullDownRefresh();
    if(app.globalData.loginInfo.client_is_store<0 && app.globalData.type_level==0 || app.globalData.loginInfo.client_is_store==0){
      this.ShouHuoCount();
    };
  },
  // 收货提醒
  ShouHuoCount:function(){
    var that = this;
    if(app.globalData.loginInfo.client_is_store<0 && app.globalData.type_level==0 || app.globalData.loginInfo.client_is_store==0){
      app.globalData.list =  averageUser; 
      app.AppHttp("api/Order/daiShouHuoCount", { 
        client_id: app.globalData.loginInfo.id, 
      }, function (res) {      
        that.setData({
          shou_hint_num:res.data.data
        });          
      }); 
      that.count_hint();    
    }
  },
  // 关闭收货提醒
  close_shou_hint:function(){
    this.setData({
      isshou_hint:false
    });
  },
  // 询价单列表
  off_list_fun:function(){
    var that = this;
    
  },
  // 订单或需求单
  updateList: function () {
    var that = this;
    if(that.data.page==1){
      wx.showLoading({
        title: that.data.load
      });
    };
    var start_time;
    var select_time=0;
    if(that.data.start_time==0){
      start_time=that.data.area_time;
    }else{
      start_time=Date.parse(new Date(that.data.start_time+'.00:00:00'));
    };
    var end_time = Date.parse(new Date(that.data.end_time+'.23:59:59'));
    if(start_time!=0){
      select_time=start_time+','+end_time
    };
    var off_list=[];
    if((app.globalData.loginInfo.client_is_store<0 && app.globalData.type_level==0 || app.globalData.loginInfo.client_is_store==0) && that.data.status==0){   //新订单&&普通版调询价单接口
      app.AppHttp('api/Client/getBelongClientEnquiry', {
        client_id:app.globalData.loginInfo.id,
        supplier_id: null,
        list_type:'order'
      }, function(res) {
        off_list=res.data.data;
        that.setData({
          off_list:res.data.data
        });
      });
    };
    var settle_accounts=1;
    var status;
    if(that.data.status==10){
      status=1;
      settle_accounts=1;
    }else if(that.data.status==11){
      status=1;
      settle_accounts=2;
    }else{
      status=that.data.status;
    };
    app.AppHttp('api/Order/latestOrder', {
      openid: app.globalData.openid,
      status:status,
      page:that.data.page,
      supplier_id: that.data.status>=10?that.data.choose_supplier_id:0,
      mode:app.globalData.loginInfo.client_is_store<0 && app.globalData.type_level==1 || app.globalData.loginInfo.client_is_store==1?'xuqiu':'caigou',
      select_time:that.data.status>=10?select_time:0,
      // select_status:app.globalData.loginInfo.client_is_store<0 && app.globalData.type_level==1 || that.data.status>0?-1001:that.data.screen_type_index
      select_status:-1001,
      settle_accounts:settle_accounts
    }, function (res) {
      app.globalData.dingdan_show = 0;
      if(res.data.status!=-1){
        var datas;
        if (that.data.page == 1){
          datas = res.data.list.list;
        }else{
          datas = that.data.datas.concat(res.data.list.list);
        };
        var update_order_list=res.data.update_order_list.list;
        update_order_list=update_order_list.concat(off_list);
        that.setData({
          loading:0,
          datas: datas,
          cur_page_index:that.data.page == 1?0:datas.length,
          helist:update_order_list.concat(datas),
          page_count: res.data.list.page_count,
          order_list: res.data.update_order_list.list,
          auth_type: res.data.auth_type,
          ftotal_num:res.data.list.count
        });
        wx.hideLoading();      
      };
    })   
  },
  // 顶部角标统计
  count_hint:function(){
    // 新订单和对账(0:'新订单',1:'对账')
    var that = this;
    app.AppHttp('api/Order/latestOrder', {
      openid: app.globalData.openid,
      status:0,
      page:1,
      supplier_id:0,
      mode:'caigou',
      select_time:0,
      select_status:-1001,
      settle_accounts:1
    }, function (res) {
      that.setData({
        new_hint_num:res.data.list.count
      }); 
    });
    app.AppHttp('api/Order/latestOrder', {
      openid: app.globalData.openid,
      status:1,
      page:1,
      supplier_id:0,
      mode:'caigou',
      select_time:0,
      select_status:-1001,
      settle_accounts:1
    }, function (res) {
      that.setData({
        dui_hint_num:res.data.list.count
      }); 
    })
  },
  // 打开筛选下拉
  open_screen:function(){
    var is_screen=this.data.is_screen;
    if(is_screen){
      util.hideBuyModal(this,"is_screen");
    }else{
      util.showBuyModal(this,-1);
      this.setData({
        is_screen:true
       });
    } 
  },
  // 关闭筛选下拉
  close_screen:function(){
    util.hideBuyModal(this,"is_screen");
  },
  // 选择供应商
  chose_super:function(){
    var that = this;
    util.showBuyModal(this);  
    that.setData({
      issuper:true
    });
    app.AppHttp("api/Order/getCBelongSupplier", {
      openid: app.globalData.openid
    }, function(res) { 
      // console.log(JSON.stringify(res.data));
      // var superlist=[{"supplier_id":"0","company_name":"全部"}];
      that.setData({
        // superlist:superlist.concat(res.data.data)
        superlist:res.data.data
      });
    });
  },
  // 确定供应商
  super_conf:function(e){
    var supplier_id=e.currentTarget.dataset.supplier_id;
    var company_name=e.currentTarget.dataset.company_name;
    this.setData({
      z_choose_supplier_id:supplier_id,
      z_choose_supplier_name:company_name
    });
    util.hideBuyModal(this,"issuper");
  },
  // 关闭供应商
  close_super:function(){
    util.hideBuyModal(this,"issuper");
  },
  // 选择筛选类型
  chose_screen_type:function(e){
    this.setData({
      z_screen_type_index:e.currentTarget.dataset.index
    });
  },
  // 选择时间段
  chose_area:function(e){
    this.setData({
      z_screen_area_index:e.currentTarget.dataset.index,
      c_start_time:0,
      c_end_time:today,
      z_start_time:0,
      z_end_time:today
    });
  },
  // 打开时间弹窗
  chose_time:function(e){
    util.showBuyModal(this);
    if(this.data.z_start_time==0){
      this.setData({
        z_start_time:today
      });
    }; 
    this.setData({
      showModalStatus:true
    });
  },
  // 关闭时间弹窗
  hideBuyModal:function(){
    util.hideBuyModal(this,"showModalStatus");
  },
  // 时间周期选中效果
  bcolor: function (e) {
    var val_time=e.currentTarget.dataset.id==1?this.data.z_end_time:this.data.z_start_time;
    if(val_time!=0){
      val_time=(val_time).split('-');
      this.setData({
        value:[val_time[0] - 2010, val_time[1]-1, val_time[2] - 1]
      });
    }
    this.setData({
      time_type: e.currentTarget.dataset.id
    });
  },
  // 年、月、日改变
  bindChange: function (e) {
    util.bindchange_time(e,this,date)
  },
  // 重置时间
  reset_time_but:function(){
    if(this.data.z_start_time!=0 || this.data.z_end_time!=today){
      this.setData({ 
        z_start_time:0, //选择开始时间
        z_end_time:today,   //选择结束时间,默认今天
      });
    };    
  },
  // 确认并关闭选择时间周期弹窗
  queding: function () {
    if (Date.parse(new Date(this.data.z_end_time)) < Date.parse(new Date(this.data.z_start_time))){
      wx.showLoading({
        title: '时间不合理',
        duration:1000
      });
    }else{
      util.hideBuyModal(this,"showModalStatus");
      this.setData({
        z_screen_area_index:-1,
        c_start_time: this.data.z_start_time,  //开始时间
        c_end_time: this.data.z_end_time,    //结束时间
      });
    }  
  },
  // 筛选查看
  screen_queding:function(){
    util.hideBuyModal(this,"is_screen");
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0
    });
    var area_time = 0;
    if(this.data.z_screen_area_index==0){  //过去1天
      area_time = Date.parse(new Date(today))-3600000 * 24
    }else if(this.data.z_screen_area_index==1){  //过去1周
      area_time = Date.parse(new Date(today))-3600000 * 24*7
    }else if(this.data.z_screen_area_index==2){  //过去30天
      area_time = Date.parse(new Date(today))-3600000 * 24*30
    };
    this.setData({
      choose_supplier_id:this.data.z_choose_supplier_id,
      choose_supplier_name:this.data.z_choose_supplier_name,
      screen_type_index:this.data.z_screen_type_index,
      screen_area_index:this.data.z_screen_area_index,
      area_time:area_time,
      start_time: this.data.c_start_time,
      end_time: this.data.c_end_time,
      loading:1,
      load:'加载中...',
      page:1
    })
    this.updateList();
  },
  // 全部重置
  screen_reset_but:function(){
    util.hideBuyModal(this,"is_screen");
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0
    });
    this.setData({
      z_choose_supplier_id:0,
      z_screen_type_index:-1001,
      z_screen_area_index:-1,
      z_start_time:0,
      z_end_time:today,
      c_start_time:0,
      c_end_time:today,
      choose_supplier_id:0,
      choose_supplier_name:'',
      screen_type_index:-1001,
      screen_area_index:-1,
      area_time:0,
      start_time:'',
      end_time:today,
      loading:1,
      load:'加载中...',
      page:1
    });
    this.updateList();
  },
  // 去首页
  toshangpin:function(){
    wx.switchTab({
      url: '/pages/shangpin/shangpin'
    });
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    if (that.data.page < that.data.page_count) {
      that.setData({
        page: that.data.page + 1,
        loading:1,
        load: '加载更多'
      });
      that.updateList();
    } else {
      that.setData({
        loading:0
      });
      wx.showToast({
        title: '没有了'
      })
    }
  }
})